/**
 * 
 */
package com.svms.sparedetails;

import java.util.Map;

import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventQueues;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Grid;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.svms.service.constants.SvmsStatusCodes;
import com.svms.service.vo.SpareCodesVO;
import com.svms.utils.SvmsMessageUtils;
import com.svms.utils.SvmsWindowUtils;
import com.svms.web.factory.SvmsWebFactory;

/**
 * @author om39a
 * 
 */
public class SpareDetailDialogueCtrl extends GenericForwardComposer<Window> {

	private Window window_spare_dialogue;

	private Button btn_close;
	private Button btn_cancle;
	private Button btn_save_spare;
	private Button btn_edit_spare;
	private Button btn_delete_spare;
	private Button btn_add_spare;

	private Textbox txb_spare_name;
	private Textbox txb_cutoff_lifetime_date;
	private Textbox txb_max_lifetime_date;
	private Textbox txb_cutoff_lifetime_dist;
	private Textbox txb_max_lifetime_dist;

	private Radio rad_date_validation;
	private Radio rad_dist_validation;
	private Radio rad_no_validation;

	private Radiogroup radio_grp_validation_type;

	private Grid grid_dist;
	private Grid grid_date;

	private ManageSpareDetailCtrl manageSpareDetailCtrl;

	private SpareCodesVO spareCodeVO;
	private SpareCodesVO oldSpareCodesVO;

	public SpareCodesVO getSpareCodeVO() {
		return spareCodeVO;
	}

	public void setSpareCodeVO(SpareCodesVO spareCodeVO) {
		this.spareCodeVO = spareCodeVO;
	}

	public SpareCodesVO getOldSpareCodesVO() {
		return oldSpareCodesVO;
	}

	public void setOldSpareCodesVO(SpareCodesVO oldSpareCodesVO) {
		this.oldSpareCodesVO = (SpareCodesVO) SerializationUtils
				.clone(oldSpareCodesVO);
	}

	/**
	 * Operation to be performed on load of the window.
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onCreate$window_spare_dialogue(Event event) throws Exception {

		Map<String, Object> args = SvmsWindowUtils.getCreationArgsMap(event);
		SpareCodesVO selectedspareCode = (SpareCodesVO) args
				.get("selectedSpareCode");

		spareCodeVO = (SpareCodesVO) SerializationUtils
				.clone(selectedspareCode);
		manageSpareDetailCtrl = (ManageSpareDetailCtrl) args
				.get("spareDetailsCtrl");

		if (getSpareCodeVO() == null) {
			// Which means edit in progress. So enable fields to edit
			newSpareDetailMapping();
			loadAddEditScenarioButtons();
			enableDefaultFields();
			showTextBoxOnRadioStatus();
		} else {
			setOldSpareCodesVO(getSpareCodeVO());
			writeBeanToDialogue(getOldSpareCodesVO());
			loadDefalutScenarioButtons();
			disableDefalutFields();
			showTextBoxOnRadioStatus();
		}

	}

	/**
	 * Operation to be performed on change of radio button
	 * 
	 * @param event
	 * @throws Exception
	 */
	public void onCheck$radio_grp_validation_type(Event event) throws Exception {
		Radio radio = radio_grp_validation_type.getSelectedItem();
		System.out.println("radio.getId() " + radio.getId());
		if ("rad_dist_validation".equals(radio.getId())) {
			System.out.println("--1--");
			grid_dist.setVisible(true);
			grid_date.setVisible(false);

		} else if ("rad_date_validation".equals(radio.getId())) {
			System.out.println("--2--");
			grid_dist.setVisible(false);
			grid_date.setVisible(true);
		} else {
			System.out.println("--3--");
			grid_dist.setVisible(false);
			grid_date.setVisible(false);
		}
	}

	private void newSpareDetailMapping() {
		setSpareCodeVO(new SpareCodesVO());
		writeBeanToDialogue(getSpareCodeVO());

	}

	/**
	 * Operation to be performed on click of add spare button. It will
	 * loadAddEditScenarioButtons and enables all editable fields
	 * 
	 * @param event
	 */
	public void onClick$btn_add_spare(Event event) {
		oldSpareCodesVO = null;
		newSpareDetailMapping();
		enableDefaultFields();
		loadAddEditScenarioButtons();
	}

	/**
	 * Operation to be performed on click of edit button. It will
	 * loadAddEditScenarioButtons and enables all editable fields
	 * 
	 * @param event
	 */
	public void onClick$btn_edit_spare(Event event) {
		enableDefaultFields();
		loadAddEditScenarioButtons();
	}

	/**
	 * Operation to be performed on click of cancel button. It will
	 * loadDefalutScenarioButtons and disables all editable fields
	 * 
	 * @param event
	 */
	public void onClick$btn_cancle(Event event) {
		writeBeanToDialogue(oldSpareCodesVO);
		setSpareCodeVO(oldSpareCodesVO);
		disableDefalutFields();
		loadDefalutScenarioButtons();
	}

	public void onClick$btn_close(Event event) {
		setSpareCodeVO(oldSpareCodesVO);
		window_spare_dialogue.detach();
	}

	/**
	 * Operation to be performed on click of save button. It performs the save
	 * operation. It will loadDefalutScenarioButtons and disables all editable
	 * fields on successful save
	 * 
	 * @param event
	 */
	public void onClick$btn_save_spare(Event event) {
		doSave();
	}

	/**
	 * Save operation by calling save method from service
	 */
	private void doSave() {

		writeDialogueToBean();

		SpareCodesVO spareCodesVO = null;

		if (StringUtils.isBlank(getSpareCodeVO().getSpareId())) {
			System.out.println("Insert New Spare invoked");

			spareCodesVO = SvmsWebFactory.spareDetailsService()
					.insertNewSpareDetail(getSpareCodeVO());

		} else {
			System.out.println("Save Spare invoked");
			System.out.println("Edit Disabled");

			spareCodesVO = SvmsWebFactory.spareDetailsService()
					.editSpareDetail(getSpareCodeVO());

		}

		// Uncomment when adding service call for movement

		/*
		 * if (movementVO.getResultCode().getErrorDetails().size() > 0) {
		 * SvmsMessageUtils.showErrorMessageFromLable(movementVO
		 * .getResultCode().getErrorDetails());
		 * writeBeanToDialogue(getOldMovementVO()); return; }
		 */

		if (false) {

		} else {

			if (manageSpareDetailCtrl != null
					&& manageSpareDetailCtrl.getLstbx_Sparecodes() != null) {

				// now synchronize the customer listBox
				ListModelList lml = (ListModelList) manageSpareDetailCtrl
						.getLstbx_Sparecodes().getListModel();

				// Check if the customer object is new or updated
				// -1 means that the obj is not in the list, so it's new.
				System.out.println("oldSpareCodesVO " + oldSpareCodesVO);
				System.out.println("getSpareCodeVO " + getSpareCodeVO());
				if (lml.indexOf(oldSpareCodesVO) == -1) {
					lml.add(getSpareCodeVO());
					System.out.println("Add Spare to main vehicle list");
					setOldSpareCodesVO(getSpareCodeVO());
				} else {
					lml.set(lml.indexOf(getOldSpareCodesVO()), getSpareCodeVO());
					System.out.println("save Movemnt to main vehicle list");
					setOldSpareCodesVO(getSpareCodeVO());
				}

			}
			SvmsMessageUtils
					.showSuccessMessage("Spare Detail Was successfully saved to the system");
			disableDefalutFields();
			loadDefalutScenarioButtons();
			
			// For the drop down in bill entry screen 
			System.out.println("Event vehicleAlertEventQueue Publicshed");
			EventQueues.lookup("spareChangeEventQueue", EventQueues.DESKTOP, true)
					.publish(new Event("onAddSpareListInBillWindow", null));
		}

		// call from cusromerList then synchronize the customers listBox

	}

	/**
	 * Operation to be performed on click of cancel button. It will
	 * loadDefalutScenarioButtons and disables all editable fields
	 * 
	 * @param event
	 */
	public void onClick$btn_delete_spare(Event event) {

		writeDialogueToBean();

		SpareCodesVO spareCodesVO;

		if (getSpareCodeVO() != null && getSpareCodeVO().getSpareId() != null) {

			spareCodesVO = SvmsWebFactory.spareDetailsService()
					.deleteSpareDetail(getSpareCodeVO());

		} else {
			SvmsMessageUtils
					.showErrorMessageFromLable(SvmsStatusCodes.SELECT_VEHICLE_TO_DELETE);
			return;
		}

		/*
		 * if (getMovementVO().getResultCode().getErrorDetails().size() > 0) {
		 * SvmsMessageUtils.showErrorMessageFromLable(vehicleVO
		 * .getResultCode().getErrorDetails()); return; }
		 */if (false) {
		} else {
			SvmsMessageUtils
					.showSuccessMessage("Spare Detail Was successfully deleted from the System");
			disableDefalutFields();
			loadDefalutScenarioButtons();
		}

		// call from cusromerList then synchronize the customers listBox
		if (manageSpareDetailCtrl != null
				&& manageSpareDetailCtrl.getLstbx_Sparecodes() != null) {

			// now synchronize the customer listBox
			final ListModelList lml = (ListModelList) manageSpareDetailCtrl
					.getLstbx_Sparecodes().getListModel();

			// Check if the customer object is new or updated
			// -1 means that the obj is not in the list, so it's new.
			if (lml.indexOf(getOldSpareCodesVO()) == -1) {
				System.out
						.println("Spare Detail not present in main Movement list");
			} else {
				lml.remove(getOldSpareCodesVO());
				System.out
						.println("Removed Spare Detail from main Movement list");
			}

		}
		window_spare_dialogue.detach();
	}

	/**
	 * To copy the contents form the individual fields in dialogue box to
	 * service for processing
	 * 
	 * @param vehicleVO
	 */
	private void writeDialogueToBean() {

		spareCodeVO.setSpareName(txb_spare_name.getValue());
		Radio radio = radio_grp_validation_type.getSelectedItem();

		if ("rad_dist_validation".equals(radio.getId())) {
			spareCodeVO.setMaxDistance(txb_max_lifetime_dist.getValue());
			spareCodeVO.setCutOffDistance(txb_cutoff_lifetime_dist.getValue());
			spareCodeVO.setValidationFormat("DIS");
		} else if ("rad_date_validation".equals(radio.getId())) {
			spareCodeVO.setMaxDays(txb_max_lifetime_date.getValue());
			spareCodeVO.setCutOffDays(txb_cutoff_lifetime_date.getValue());
			spareCodeVO.setValidationFormat("DAY");
		} else {
			spareCodeVO.setMaxDistance("0");
			spareCodeVO.setCutOffDistance("0");
			spareCodeVO.setMaxDays("0");
			spareCodeVO.setCutOffDays("0");
			spareCodeVO.setValidationFormat("NA");
		}

	}

	private void writeBeanToDialogue(SpareCodesVO spareCodeVO) {

		if (spareCodeVO != null) {

			txb_cutoff_lifetime_date.setValue(spareCodeVO.getCutOffDays());
			txb_cutoff_lifetime_dist.setValue(spareCodeVO.getCutOffDistance());
			txb_max_lifetime_date.setValue(spareCodeVO.getMaxDays());
			txb_max_lifetime_dist.setValue(spareCodeVO.getMaxDistance());
			txb_spare_name.setValue(spareCodeVO.getSpareName());

			if ("DIS".equals(spareCodeVO.getValidationFormat())) {
				rad_dist_validation.setSelected(true);
			} else if ("DAY".equals(spareCodeVO.getValidationFormat())) {
				rad_date_validation.setSelected(true);
			} else {
				rad_no_validation.setSelected(true);
			}

		}
	}

	private void loadAddEditScenarioButtons() {

		btn_add_spare.setDisabled(true);
		btn_delete_spare.setDisabled(true);
		btn_edit_spare.setDisabled(true);
		btn_save_spare.setDisabled(false);

		btn_cancle.setDisabled(false);
		btn_close.setDisabled(false);

	}

	private void enableDefaultFields() {

		txb_cutoff_lifetime_date.setDisabled(false);
		txb_cutoff_lifetime_dist.setDisabled(false);
		txb_max_lifetime_date.setDisabled(false);
		txb_max_lifetime_dist.setDisabled(false);

		txb_spare_name.setDisabled(false);

	}

	private void disableDefalutFields() {

		txb_cutoff_lifetime_date.setDisabled(true);
		txb_cutoff_lifetime_dist.setDisabled(true);
		txb_max_lifetime_date.setDisabled(true);
		txb_max_lifetime_dist.setDisabled(true);

		txb_spare_name.setDisabled(true);

	}

	private void showTextBoxOnRadioStatus() {

		if (rad_dist_validation.isSelected()) {

			grid_dist.setVisible(true);
			grid_date.setVisible(false);

		} else if (rad_date_validation.isSelected()) {

			grid_dist.setVisible(false);
			grid_date.setVisible(true);

		} else {
			grid_dist.setVisible(false);
			grid_date.setVisible(false);
		}
	}

	/**
	 * Will load DEFAULT CURD buttons. Is same for DEFALUT, SAVE, DISCARD
	 */
	private void loadDefalutScenarioButtons() {

		btn_add_spare.setDisabled(false);
		btn_delete_spare.setDisabled(false);
		btn_edit_spare.setDisabled(false);
		btn_save_spare.setDisabled(true);

		showTextBoxOnRadioStatus();

		btn_cancle.setDisabled(true);
		btn_close.setDisabled(false);
	}

}
